package com.mengxuegu.springboot.controller;

import com.mengxuegu.springboot.dao.ProviderDao;
import com.mengxuegu.springboot.entities.Bill;
import com.mengxuegu.springboot.entities.BillProvider;
import com.mengxuegu.springboot.entities.Provider;
import com.mengxuegu.springboot.mapper.BillMapper;
import com.mengxuegu.springboot.mapper.ProviderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Controller
public class BillController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ProviderMapper providerMapper;

    @Autowired
    BillMapper billMapper;

    //    @RequestMapping(value = "/providers", method = RequestMethod.GET)
    @GetMapping("/bills")
    public String list(Map<String, Object> map, Bill bill) {
        logger.info("账单列表查询。。。" + bill);

        List<BillProvider> billProviders = billMapper.getBills(bill);

        List<Provider> providers = providerMapper.getProviders(null);

        map.put("billProviders", billProviders);
        map.put("providers", providers);
        map.put("billName", bill.getBillName());
        map.put("pid", bill.getPid());
        map.put("pay", bill.getPay());
        return "bill/list";
    }

    @GetMapping("/bill/{pid}")
    public String view(@PathVariable("pid") Integer bid,
                       @RequestParam(value = "type", defaultValue = "view") String type,
                       Map<String, Object> map) {
        logger.info("查询" + bid + "的供应商详细信息");

        BillProvider billProvider = billMapper.getBillByBid(bid);

        if("update".equals(type)) {
            List<Provider> providers = providerMapper.getProviders(null);
            map.put("providers", providers);
        }

        map.put("billProvider", billProvider);
//        return "provider/view";
        return "bill/" + type;
    }

    @PutMapping("/bill")
    public String update(Bill bill) {
        logger.info("更新订单信息");

        billMapper.updateBill(bill);
        return "redirect:bills";
    }

    @GetMapping("/bill")
    public String toAddPage(Map<String, Object> map) {
        map.put("providers", providerMapper.getProviders(null));
        return "bill/add";
    }

    @PostMapping("/bill")
    public String add(Bill bill) {
        logger.info("添加数据" + bill);

        billMapper.addBill(bill);
        return "redirect:/bills";
    }

    @DeleteMapping("/bill/{pid}")
    public String delete(@PathVariable("pid") Integer pid) {
        logger.info("删除操作,pid=" + pid);
        billMapper.deleteBillByBid(pid);
        return "redirect:/providers";
    }

}
